package com.songyang.mybatis.binding;

import cn.hutool.core.lang.ClassScanner;
import com.songyang.mybatis.session.Configuration;
import com.songyang.mybatis.session.SqlSession;

import java.util.HashMap;
import java.util.Map;
import java.util.Set;

/**
 * @ClassName MapperRegister
 * @Description 映射器注册机
 * @date 2023/3/20 15:26
 * @Author yanceysong
 * @Version 1.0
 */
public class MapperRegistry {
    private final Configuration config;
    /**
     * 将已添加的映射器代理加入到 HashMap
     */
    private final Map<Class<?>, MapperProxyFactory<?>> knownMappers = new HashMap<>();

    public MapperRegistry(Configuration config) {
        this.config = config;
    }

    /**
     * 在已知的映射代理类中获取一个代理类
     *
     * @param type       接口类
     * @param sqlSession sql的会话
     * @param <T>        泛型可以是任何类
     * @return 获取的代理类
     */
    @SuppressWarnings("unchecked")
    public <T> T getMapper(Class<T> type, SqlSession sqlSession) {
        final MapperProxyFactory<T> mapperProxyFactory = (MapperProxyFactory<T>) knownMappers.get(type);
        if (mapperProxyFactory == null) {
            throw new RuntimeException("Type " + type + " is not known to the MapperRegistry.");
        }
        try {
            return mapperProxyFactory.newInstance(sqlSession);
        } catch (Exception e) {
            throw new RuntimeException("Error getting mapper instance. Cause: " + e, e);
        }
    }

    /**
     * 注册机添加映射类
     *
     * @param type 类型
     * @param <T>  泛型可以是任何类
     */
    public <T> void addMapper(Class<T> type) {
        /* Mapper 必须是接口才会注册 */
        if (type.isInterface()) {
            if (hasMapper(type)) {
                // 如果重复添加了，报错
                throw new RuntimeException("Type " + type + " is already known to the MapperRegistry.");
            }
            // 注册映射器代理工厂
            knownMappers.put(type, new MapperProxyFactory<>(type));
        }
    }

    /**
     * 检查当前是否已经有这个类的代理类
     *
     * @param type 类的类型
     * @param <T>  泛型 可以是任何类
     * @return 检查结果
     */
    public <T> boolean hasMapper(Class<T> type) {
        return knownMappers.containsKey(type);
    }

    /**
     * 根据包的路径扫描所有的接口，添加并存储对应的代理类工厂
     *
     * @param packageName 包的名字
     */
    public void addMappers(String packageName) {
        Set<Class<?>> mapperSet = ClassScanner.scanPackage(packageName);
        for (Class<?> mapperClass : mapperSet) {
            addMapper(mapperClass);
        }
    }
}
